import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../../../assets/styles.dart';
import '../../../../components/circle_image.dart';
import '../../../../components/easy_toast.dart';
import '../../../../components/image_view.dart';
import '../../../../generate/app_image_path.dart';
import '../../../../http/api/api.dart';
import '../../../../model/advertisements/ad_resp_model.dart';
import '../../../../model/play/video_detail_model.dart';
import '../../../../routes/routes.dart';
import '../../../../services/app_service.dart';
import '../../../../utils/ad_jump.dart';
import '../../../../utils/busy_future.dart';
import '../../../../utils/enum.dart';
import '../../../../utils/extension.dart';
import '../../../../utils/initAdvertisementInfo.dart';
import '../../../../utils/utils.dart';

///
/// 右边操作 广告，关注，LIKE， 分享
///
class ShortVPOperationArea extends StatefulWidget {
  final VideoDetail detail;
  final double topHeight;

  // final bool Function() onTapUnmute;
  final VoidCallback onTapUnmute;

  // final bool webUnmuteTouched;
  final bool webMuted;

  const ShortVPOperationArea(
    this.detail, {
    super.key,
    required this.topHeight,
    required this.onTapUnmute,
    // required this.webUnmuteTouched,
    required this.webMuted,
  });

  @override
  State<StatefulWidget> createState() => _State();
}

class _State extends State<ShortVPOperationArea> with BusyFuture {
  VideoDetail get detail => widget.detail;

  Future<void> _onTapAttention() async {
    final old = detail.attention ?? false;
    final result = await busyCall(
      'attention',
      () => Api.focusAction(
        userId: detail.userId ?? 0,
        attention: old,
      ),
    );
    if (!result.item1) return;
    if (result.item2 == true) {
      if (!mounted) return;
      EasyToast.show(old ? '取消成功' : '关注成功');
      setState(() {
        detail.attention = !old;
      });
    }
  }

  Future<void> _onTapLike() async {
    final old = detail.like ?? false;
    final result = await busyCall(
      'like',
      () => Api.toogleVideoLike(
        detail.videoId ?? 0,
        like: old,
      ),
    );
    if (!result.item1) return;
    if (result.item2 == true) {
      if (!mounted) return;
      EasyToast.show(old ? '取消成功' : '收藏成功');
      setState(() {
        detail.like = !old;
        if (detail.like == true) {
          detail.fakeLikes = (detail.fakeLikes ?? 0) + 1;
        } else {
          detail.fakeLikes = (detail.fakeLikes ?? 1) - 1;
        }
      });
    }
  }

  Widget _buildMutedButton() {
    if (!kIsWeb) return const SizedBox.shrink();
    // if (!widget.webMuted) {
    //   return Icon(Icons.volume_off, size: 35.w, color: Colors.white)
    //       .onTap(widget.onTapUnmute);
    // } else {
    //   return const SizedBox.shrink();
    // }
    return Icon(widget.webMuted ? Icons.volume_off : Icons.volume_up,
            size: 35.w, color: Colors.white)
        .onTap(widget.onTapUnmute);
  }

  Widget _buildAd(AdvertisementInfos ad, double width) {
    return Obx(() {
      if (Get.find<AppService>().shortShowAd) {
        return Column(
          children: [
            Image.asset(AppImagePath.short_close_ad, width: 18.w, height: 18.w)
                .onTap(() => Get.find<AppService>().hideShortAd()),
            10.verticalSpaceFromWidth,
            ImageView(
              src: ad.adImage ?? '',
              width: width,
              height: width,
              borderRadius: Styles.borderRadius.all(8.w),
            ).onTap(() => kAdInfoJump(ad)),
          ],
        ).marginBottom(18.w);
      }
      return const SizedBox.shrink();
    });
  }

  Widget _buildLogo() {
    return Visibility(
      visible: true,
      child: Stack(
        clipBehavior: Clip.none,
        children: [
          CircleImage.network(
            detail.logo ?? '',
            size: 46.w,
            onTap: () {},
          ),
          Positioned(
            left: 14.w,
            bottom: -8.w,
            child: Image.asset(
              detail.attention == true
                  ? AppImagePath.short_short_focus_y
                  : AppImagePath.short_short_focus,
              width: 20.w,
              height: 20.w,
            ).onTap(_onTapAttention),
          )
        ],
      ),
    );
  }

  Widget _buildBtn({
    required String name,
    required String icon,
    required VoidCallback onTap,
    required double iconW,
    bool alwaryVisiable = false,
  }) {
    bool visible = true;
    if (alwaryVisiable) {
      visible = true;
    }
    return Visibility(
      visible: visible,
      child: Column(
        children: [
          Image.asset(
            icon,
            width: iconW,
            fit: BoxFit.fitWidth,
          ),
          if (name.isNotEmpty) ...[
            SizedBox(height: 2.w),
            Text(
              name,
              maxLines: 1,
              textAlign: TextAlign.center,
              style: TextStyle(color: Colors.white, fontSize: 12.w),
            )
          ]
        ],
      ).onTap(onTap),
    );
  }

  Widget _buildLike() => _buildBtn(
        name: Utils.numFmtCh(detail.fakeLikes ?? 0),
        icon: detail.like == true
            ? AppImagePath.short_short_like_y
            : AppImagePath.short_short_like,
        onTap: _onTapLike,
        iconW: 31.w,
      );

  Widget _buildShare() => _buildBtn(
        name: '分享',
        icon: AppImagePath.short_short_share,
        onTap: () => Get.toShare(),
        iconW: 29.w,
      );

  @override
  Widget build(BuildContext context) {
    final ad =
        initSequenceAdvertisementInfo(AdPlaceNameEnum.SV_BRUSH_RIGHT_LEVITATE)
            .firstOrNull;
    final width = 60.w;
    return Container(
      width: width,
      margin: EdgeInsets.only(right: 4.w),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          if (ad != null) _buildAd(ad, width),
          _buildLogo(),
          SizedBox(height: 30.w),
          _buildLike(),
          SizedBox(height: 15.w),
          _buildShare(),
          SizedBox(height: 15.w),
          _buildMutedButton(),
        ],
      ),
    );
  }
}
